package com.liting.uitest.imgutils;

import com.liting.uitest.model.Circle;
import com.liting.uitest.model.ImageInfo;
import com.liting.uitest.model.Rectangle;
import com.liting.uitest.service.impl.ImageCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * 比例感计算
 */
@Service
@Slf4j
public class Proportion {
    private static List<Double> goodProportionList = new ArrayList() {{
        add(1.0);
        add(1.3);
        add(1.4);
        add(1.6);
        add(1.7);
        add(2.0);
        add(2.4);
        add(2.6);
        add(3.3);
    }};

    @Autowired
    private ImageCacheService cacheService;

    public BigDecimal proportionCalc(Long fileId, List<Rectangle> rectList, List<Circle> cirList) throws Exception {
        ImageInfo imageInfo = cacheService.getImage(fileId);
        if (imageInfo == null) {
            throw new Exception("文件不存在");
        }

        int goodNum = 0, allNum = 0;

        if (rectList != null) {
            for (Rectangle rectangle : rectList) {
                BigDecimal rectPropor = rectangle.getProportion();
                log.info("rect proportion is " + rectPropor);
                if (isGoodProportion(rectPropor)) {
                    goodNum++;
                }
                allNum++;
            }
        }
        if (cirList != null) {
            goodNum = goodNum + cirList.size();//圆形都是好比例
            allNum = allNum + cirList.size();
        }

        return BigDecimal.valueOf(goodNum / (double) allNum).setScale(1, RoundingMode.UP);
    }

    private boolean isGoodProportion(BigDecimal proportion) {
        for (Double goodProp : goodProportionList) {
            if (goodProp == proportion.doubleValue()) {
                return true;
            }
        }
        return false;
    }
}
